const Parse = require('parse/node');
const WhiteListObj = Parse.Object.extend("AutoBorrow_WhiteList");
const WhiteListMemberObj = Parse.Object.extend("AutoBorrow_WhiteListMember");
const WhiteListPickupObj = Parse.Object.extend("AutoBorrow_WhiteListPickup");
const WhiteListPickupItemObj = Parse.Object.extend("AutoBorrow_WhiteListPickupItem");
const ParseHelper = require('../helpers/parse');
const ExcelService = require("./excel");
const UserService = require('./user_enhanced');
const moment = require('moment');
const _ = require('lodash');

/**
 * 白名单管理服务 - 增强版本
 * 支持白名单创建、成员管理、物品领取、负责人管理
 */

// 白名单状态
const WHITELIST_STATUS = {
    ACTIVE: 'active',
    INACTIVE: 'inactive',
    ARCHIVED: 'archived'
};

// 成员状态
const MEMBER_STATUS = {
    ACTIVE: 'active',
    INACTIVE: 'inactive',
    SUSPENDED: 'suspended'
};

// 领取状态
const PICKUP_STATUS = {
    PENDING: 'pending',      // 待领取
    APPROVED: 'approved',    // 已批准
    PICKED_UP: 'picked_up',  // 已领取
    RETURNED: 'returned',    // 已归还
    CANCELLED: 'cancelled'   // 已取消
};

/**
 * 创建白名单
 * @param {Object} whitelistData - 白名单数据
 * @returns {Promise<Object>} 创建结果
 */
async function createWhiteList(whitelistData) {
    try {
        const whitelist = new WhiteListObj();
        whitelist.set('name', whitelistData.name);
        whitelist.set('description', whitelistData.description || '');
        whitelist.set('managerId', whitelistData.managerId);
        whitelist.set('managerName', whitelistData.managerName || '');
        whitelist.set('status', WHITELIST_STATUS.ACTIVE);
        whitelist.set('isActive', true);
        whitelist.set('createdAt', new Date());
        whitelist.set('updatedAt', new Date());
        
        await whitelist.save(null, { useMasterKey: true });
        
        return {
            success: true,
            whitelist: ParseHelper.toJSON(whitelist),
            message: '白名单创建成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 添加成员到白名单
 * @param {string} whitelistId - 白名单ID
 * @param {Array} memberData - 成员数据数组
 * @returns {Promise<Object>} 添加结果
 */
async function addMembersToWhiteList(whitelistId, memberData) {
    try {
        const results = {
            success: 0,
            failed: 0,
            errors: []
        };

        for (const member of memberData) {
            try {
                // 检查成员是否已存在
                const existingMember = await getWhiteListMember(whitelistId, member.username);
                if (existingMember) {
                    results.failed++;
                    results.errors.push({
                        username: member.username,
                        error: '成员已存在'
                    });
                    continue;
                }

                // 验证用户是否存在
                const user = await UserService.getUserByUsername(member.username);
                if (!user) {
                    results.failed++;
                    results.errors.push({
                        username: member.username,
                        error: '用户不存在'
                    });
                    continue;
                }

                // 添加成员
                const whitelistMember = new WhiteListMemberObj();
                whitelistMember.set('whitelistId', whitelistId);
                whitelistMember.set('userId', user.objectId);
                whitelistMember.set('username', member.username);
                whitelistMember.set('showName', user.showName);
                whitelistMember.set('studentNumber', user.studentNumber);
                whitelistMember.set('class_name', user.class_name);
                whitelistMember.set('status', MEMBER_STATUS.ACTIVE);
                whitelistMember.set('joinedAt', new Date());
                whitelistMember.set('createdAt', new Date());
                
                await whitelistMember.save(null, { useMasterKey: true });
                results.success++;
                
            } catch (error) {
                results.failed++;
                results.errors.push({
                    username: member.username,
                    error: error.message
                });
            }
        }

        return {
            success: true,
            results,
            message: `成功添加 ${results.success} 个成员，失败 ${results.failed} 个成员`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取白名单成员
 * @param {string} whitelistId - 白名单ID
 * @param {string} username - 用户名
 * @returns {Promise<Object>} 成员信息
 */
async function getWhiteListMember(whitelistId, username) {
    try {
        const query = new Parse.Query(WhiteListMemberObj);
        query.equalTo('whitelistId', whitelistId);
        query.equalTo('username', username);
        query.notEqualTo('isDeleted', true);
        
        const member = await query.first({ useMasterKey: true });
        return member ? ParseHelper.toJSON(member) : null;
    } catch (error) {
        return null;
    }
}

/**
 * 获取白名单成员列表
 * @param {string} whitelistId - 白名单ID
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 成员列表
 */
async function getWhiteListMembers(whitelistId, options = {}) {
    try {
        const {
            status,
            page = 1,
            limit = 10,
            search
        } = options;

        const query = new Parse.Query(WhiteListMemberObj);
        query.equalTo('whitelistId', whitelistId);
        query.notEqualTo('isDeleted', true);

        if (status) {
            query.equalTo('status', status);
        }

        if (search) {
            const searchQuery1 = new Parse.Query(WhiteListMemberObj);
            searchQuery1.contains('username', search);
            
            const searchQuery2 = new Parse.Query(WhiteListMemberObj);
            searchQuery2.contains('showName', search);
            
            query._orQuery([searchQuery1, searchQuery2]);
        }

        query.descending('createdAt');
        
        const skip = (page - 1) * limit;
        query.skip(skip);
        query.limit(limit);

        const [members, total] = await Promise.all([
            query.find({ useMasterKey: true }),
            query.count({ useMasterKey: true })
        ]);

        return {
            success: true,
            members: members.map(member => ParseHelper.toJSON(member)),
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 删除白名单成员
 * @param {string} whitelistId - 白名单ID
 * @param {Array} usernames - 用户名数组
 * @returns {Promise<Object>} 删除结果
 */
async function removeMembersFromWhiteList(whitelistId, usernames) {
    try {
        const query = new Parse.Query(WhiteListMemberObj);
        query.equalTo('whitelistId', whitelistId);
        query.containedIn('username', usernames);
        query.notEqualTo('isDeleted', true);
        
        const members = await query.find({ useMasterKey: true });
        
        const updatePromises = members.map(member => {
            member.set('isDeleted', true);
            member.set('deletedAt', new Date());
            return member.save(null, { useMasterKey: true });
        });
        
        await Promise.all(updatePromises);
        
        return {
            success: true,
            message: `成功删除 ${members.length} 个成员`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 创建白名单物品领取
 * @param {Object} pickupData - 领取数据
 * @returns {Promise<Object>} 创建结果
 */
async function createWhiteListPickup(pickupData) {
    try {
        const pickup = new WhiteListPickupObj();
        pickup.set('whitelistId', pickupData.whitelistId);
        pickup.set('title', pickupData.title);
        pickup.set('description', pickupData.description || '');
        pickup.set('pickupCode', generatePickupCode());
        pickup.set('createdBy', pickupData.createdBy);
        pickup.set('expectedPickupDate', pickupData.expectedPickupDate || null);
        pickup.set('status', PICKUP_STATUS.PENDING);
        pickup.set('isActive', true);
        pickup.set('createdAt', new Date());
        pickup.set('updatedAt', new Date());
        
        await pickup.save(null, { useMasterKey: true });
        
        // 添加物品清单
        if (pickupData.items && pickupData.items.length > 0) {
            await addItemsToPickup(pickup.id, pickupData.items);
        }
        
        return {
            success: true,
            pickup: ParseHelper.toJSON(pickup),
            message: '物品领取创建成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 添加物品到领取清单
 * @param {string} pickupId - 领取ID
 * @param {Array} items - 物品数组
 * @returns {Promise<Object>} 添加结果
 */
async function addItemsToPickup(pickupId, items) {
    try {
        const pickupItems = [];
        
        for (const item of items) {
            const pickupItem = new WhiteListPickupItemObj();
            pickupItem.set('pickupId', pickupId);
            pickupItem.set('materialId', item.materialId);
            pickupItem.set('materialName', item.materialName);
            pickupItem.set('quantity', item.quantity);
            pickupItem.set('unit', item.unit || '个');
            pickupItem.set('remark', item.remark || '');
            pickupItem.set('createdAt', new Date());
            
            pickupItems.push(pickupItem);
        }
        
        await Parse.Object.saveAll(pickupItems, { useMasterKey: true });
        
        return {
            success: true,
            message: `成功添加 ${pickupItems.length} 个物品`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 根据领取码获取领取信息
 * @param {string} pickupCode - 领取码
 * @returns {Promise<Object>} 领取信息
 */
async function getPickupByCode(pickupCode) {
    try {
        const query = new Parse.Query(WhiteListPickupObj);
        query.equalTo('pickupCode', pickupCode);
        query.notEqualTo('isDeleted', true);
        
        const pickup = await query.first({ useMasterKey: true });
        if (!pickup) {
            return {
                success: false,
                error: '领取码不存在或已失效'
            };
        }
        
        // 获取物品清单
        const itemsQuery = new Parse.Query(WhiteListPickupItemObj);
        itemsQuery.equalTo('pickupId', pickup.id);
        itemsQuery.notEqualTo('isDeleted', true);
        
        const items = await itemsQuery.find({ useMasterKey: true });
        
        const pickupData = ParseHelper.toJSON(pickup);
        pickupData.items = items.map(item => ParseHelper.toJSON(item));
        
        return {
            success: true,
            pickup: pickupData
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 确认物品领取
 * @param {string} pickupId - 领取ID
 * @param {Object} confirmData - 确认数据
 * @returns {Promise<Object>} 确认结果
 */
async function confirmPickup(pickupId, confirmData) {
    try {
        const pickup = WhiteListPickupObj.createWithoutData(pickupId);
        pickup.set('status', PICKUP_STATUS.PICKED_UP);
        pickup.set('pickedUpBy', confirmData.pickedUpBy);
        pickup.set('pickedUpAt', new Date());
        pickup.set('confirmRemark', confirmData.remark || '');
        pickup.set('updatedAt', new Date());
        
        await pickup.save(null, { useMasterKey: true });
        
        return {
            success: true,
            message: '物品领取确认成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 批量导入白名单成员
 * @param {string} whitelistId - 白名单ID
 * @param {string} filePath - 文件路径
 * @param {Object} options - 导入选项
 * @returns {Promise<Object>} 导入结果
 */
async function importMembersFromExcel(whitelistId, filePath, options = {}) {
    try {
        const {
            nameRowNumber = 1,
            firstDataRowNumber = 2,
            fieldsMapping = {}
        } = options;

        const membersData = await ExcelService.parseExcelFileFirstSheet(
            filePath,
            nameRowNumber,
            firstDataRowNumber
        );

        if (!membersData || membersData.length === 0) {
            throw new Error('Excel文件没有有效数据');
        }

        // 数据映射
        const mappedMembersData = membersData.map(memberData => {
            const mappedData = {};
            Object.keys(memberData).forEach(key => {
                const dbFieldName = fieldsMapping[key] || key;
                mappedData[dbFieldName] = memberData[key];
            });
            return mappedData;
        });

        // 批量添加成员
        const result = await addMembersToWhiteList(whitelistId, mappedMembersData);
        
        return result;
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取白名单列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 白名单列表
 */
async function getWhiteListList(options = {}) {
    try {
        const {
            status,
            managerId,
            page = 1,
            limit = 10,
            search
        } = options;

        const query = new Parse.Query(WhiteListObj);
        query.notEqualTo('isDeleted', true);

        if (status) {
            query.equalTo('status', status);
        }

        if (managerId) {
            query.equalTo('managerId', managerId);
        }

        if (search) {
            const searchQuery1 = new Parse.Query(WhiteListObj);
            searchQuery1.contains('name', search);
            
            const searchQuery2 = new Parse.Query(WhiteListObj);
            searchQuery2.contains('managerName', search);
            
            query._orQuery([searchQuery1, searchQuery2]);
        }

        query.descending('createdAt');
        
        const skip = (page - 1) * limit;
        query.skip(skip);
        query.limit(limit);

        const [whitelists, total] = await Promise.all([
            query.find({ useMasterKey: true }),
            query.count({ useMasterKey: true })
        ]);

        return {
            success: true,
            whitelists: whitelists.map(whitelist => ParseHelper.toJSON(whitelist)),
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取白名单列表（别名方法，用于API兼容）
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 白名单列表
 */
async function getWhitelists(options = {}) {
    // 参数映射，适配不同的参数名
    const mappedOptions = {
        page: options.page || 1,
        limit: options.pageSize || options.limit || 10,
        search: options.search || '',
        status: options.status || '',
        managerId: options.managerId || ''
    };
    
    return await getWhiteListList(mappedOptions);
}

/**
 * 获取白名单物品领取列表
 * @param {string} whitelistId - 白名单ID
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 领取列表
 */
async function getWhiteListPickupList(whitelistId, options = {}) {
    try {
        const {
            status,
            page = 1,
            limit = 10
        } = options;

        const query = new Parse.Query(WhiteListPickupObj);
        query.equalTo('whitelistId', whitelistId);
        query.notEqualTo('isDeleted', true);

        if (status) {
            query.equalTo('status', status);
        }

        query.descending('createdAt');
        
        const skip = (page - 1) * limit;
        query.skip(skip);
        query.limit(limit);

        const [pickups, total] = await Promise.all([
            query.find({ useMasterKey: true }),
            query.count({ useMasterKey: true })
        ]);

        return {
            success: true,
            pickups: pickups.map(pickup => ParseHelper.toJSON(pickup)),
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 生成领取码
 * @returns {string} 领取码
 */
function generatePickupCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < 8; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

/**
 * 创建白名单（别名方法，用于API兼容）
 * @param {Object} whitelistData - 白名单数据
 * @returns {Promise<Object>} 创建结果
 */
async function createWhitelist(whitelistData) {
    return await createWhiteList(whitelistData);
}

/**
 * 更新白名单
 * @param {string} whitelistId - 白名单ID
 * @param {Object} updateData - 更新数据
 * @returns {Promise<Object>} 更新结果
 */
async function updateWhitelist(whitelistId, updateData) {
    try {
        const whitelist = WhiteListObj.createWithoutData(whitelistId);
        
        if (updateData.name) {
            whitelist.set('name', updateData.name);
        }
        if (updateData.description !== undefined) {
            whitelist.set('description', updateData.description);
        }
        if (updateData.managerId) {
            whitelist.set('managerId', updateData.managerId);
        }
        if (updateData.managerName) {
            whitelist.set('managerName', updateData.managerName);
        }
        if (updateData.status) {
            whitelist.set('status', updateData.status);
        }
        if (updateData.isActive !== undefined) {
            whitelist.set('isActive', updateData.isActive);
        }
        
        whitelist.set('updatedAt', new Date());
        
        await whitelist.save(null, { useMasterKey: true });
        
        return {
            success: true,
            message: '白名单更新成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 删除白名单
 * @param {string} whitelistId - 白名单ID
 * @returns {Promise<Object>} 删除结果
 */
async function deleteWhitelist(whitelistId) {
    try {
        const whitelist = WhiteListObj.createWithoutData(whitelistId);
        whitelist.set('isDeleted', true);
        whitelist.set('deletedAt', new Date());
        whitelist.set('updatedAt', new Date());
        
        await whitelist.save(null, { useMasterKey: true });
        
        return {
            success: true,
            message: '白名单删除成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 添加成员到白名单（别名方法，用于API兼容）
 * @param {string} whitelistId - 白名单ID
 * @param {Array} userIds - 用户ID数组或用户名数组
 * @returns {Promise<Object>} 添加结果
 */
async function addMembers(whitelistId, userIds) {
    // 如果传入的是用户ID数组，需要转换成用户名数组
    try {
        const memberData = [];
        
        for (const userId of userIds) {
            // 检查是否是用户ID格式（10位字符）还是用户名格式
            if (userId.length === 10 && /^[a-zA-Z0-9]{10}$/.test(userId)) {
                // 是用户ID，需要查找用户名
                const user = await UserService.getUserById(userId);
                if (user) {
                    memberData.push({ username: user.username });
                }
            } else {
                // 是用户名，直接使用
                memberData.push({ username: userId });
            }
        }
        
        return await addMembersToWhiteList(whitelistId, memberData);
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 从白名单移除成员（别名方法，用于API兼容）
 * @param {string} whitelistId - 白名单ID
 * @param {Array} userIds - 用户ID数组或用户名数组
 * @returns {Promise<Object>} 移除结果
 */
async function removeMembers(whitelistId, userIds) {
    // 如果传入的是用户ID数组，需要转换成用户名数组
    try {
        const usernames = [];
        
        for (const userId of userIds) {
            // 检查是否是用户ID格式（10位字符）还是用户名格式
            if (userId.length === 10 && /^[a-zA-Z0-9]{10}$/.test(userId)) {
                // 是用户ID，需要查找用户名
                const user = await UserService.getUserById(userId);
                if (user) {
                    usernames.push(user.username);
                }
            } else {
                // 是用户名，直接使用
                usernames.push(userId);
            }
        }
        
        return await removeMembersFromWhiteList(whitelistId, usernames);
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

module.exports = {
    createWhiteList,
    createWhitelist, // 添加别名方法
    updateWhitelist, // 添加更新方法
    deleteWhitelist, // 添加删除方法
    addMembersToWhiteList,
    addMembers, // 添加别名方法
    getWhiteListMember,
    getWhiteListMembers,
    removeMembersFromWhiteList,
    removeMembers, // 添加别名方法
    createWhiteListPickup,
    addItemsToPickup,
    getPickupByCode,
    confirmPickup,
    importMembersFromExcel,
    getWhiteListList,
    getWhitelists, // 添加别名方法
    getWhiteListPickupList,
    WHITELIST_STATUS,
    MEMBER_STATUS,
    PICKUP_STATUS
};
